/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swa.e_store.businessLogic;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import swa.e_store.entity.Reorder;
import swa.e_store.entity.OrderItem;
import javax.persistence.*;
import javax.swing.JOptionPane;
import swa.e_store.entity.Article;
import swa.e_store.entity.Purchase;
import swa.e_store.entity.PurchaseItem;
import swa.e_store.entity.Stock;

/**
 * This class contains all business logic functionality related to orderings.
 * This can be Customer-Orders or ReOrdering from centralized Stock.
 * 
 * 
 * @author Stefan
 */
public class BL_Order {

    private static final int MINSTOCK = 5;

    public Reorder placeReorder(ArrayList<OrderItem> orderItemList, int USRID, String date) {

        //EMFactory
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Napier_E-StorePU");

        //EntityManager
        EntityManager eManager = emFactory.createEntityManager();

        //Start Transaction
        EntityTransaction tx = eManager.getTransaction();
        tx.begin();



        Reorder reorder = new Reorder(0, USRID, date);
        eManager.persist(reorder);

        tx.commit();
        tx.begin();

        OrderItem tmpOItem = new OrderItem();

        Iterator<OrderItem> it = orderItemList.iterator();
        while (it.hasNext()) {
            tmpOItem = it.next();
            tmpOItem.setOrderId(reorder.getOrderId());
            eManager.persist(tmpOItem);
        }

        tx.commit();

        fillStock(orderItemList);

        //dispose
        eManager.close();
        emFactory.close();

        return reorder;

    }

    private void fillStock(ArrayList<OrderItem> orderItemList) {

        //EMFactory
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Napier_E-StorePU");

        //EntityManager
        EntityManager eManager = emFactory.createEntityManager();

        //Start Transaction
        EntityTransaction tx = eManager.getTransaction();
        tx.begin();



        Stock tmpStockItem = new Stock();
        OrderItem tmpOItem = new OrderItem();

        Iterator<OrderItem> it = orderItemList.iterator();
        while (it.hasNext()) {
            tmpOItem = it.next();
            tmpStockItem = eManager.find(Stock.class, tmpOItem.getArtNbr());
            tmpStockItem.setQuantity(tmpStockItem.getQuantity() + tmpOItem.getQuantity());
            eManager.persist(tmpStockItem);
        }

        tx.commit();

        //dispose
        eManager.close();
        emFactory.close();

    }

    public void setPurchase(ArrayList<PurchaseItem> purchaseItemList, int customerId, String date) {

        //EMFactory
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Napier_E-StorePU");

        //EntityManager
        EntityManager eManager = emFactory.createEntityManager();

        //Start Transaction
        EntityTransaction tx = eManager.getTransaction();
        tx.begin();



        Purchase purchase = new Purchase(customerId, date);
        eManager.persist(purchase);

        tx.commit();
        tx.begin();

        long lineAmount;

        PurchaseItem tmpPItem = new PurchaseItem();

        Iterator<PurchaseItem> it = purchaseItemList.iterator();
        while (it.hasNext()) {
            tmpPItem = it.next();
            tmpPItem.setPurchaseId(purchase.getPurchaseId());
            //Unitprice
            Article article = eManager.find(Article.class, tmpPItem.getArtNbr());
            tmpPItem.setUnitPrice(article.getPrice());
            //lineAmount
            tmpPItem.setLineamount(tmpPItem.getUnitPrice() * tmpPItem.getQuantity());           
            eManager.persist(tmpPItem);
        }
        
  //      tx.commit();
            
//            //PurchaseAmount
            List<PurchaseItem> piList = eManager.createNamedQuery("purchaseItem.findByPurchaseId").setParameter("purchaseId", purchase.getPurchaseId()).getResultList();
            float totalAmount = 0f;
            PurchaseItem tmpPItem2 = new PurchaseItem();
            
            Iterator<PurchaseItem> itr = piList.iterator();
            while(itr.hasNext()) {
                tmpPItem2 = itr.next();
                totalAmount += tmpPItem2.getLineamount();
            }
            purchase.setPrice(totalAmount);
            
            eManager.persist(purchase);
          
          //Test
//            purchase.setPrice(999.9f);
//            eManager.persist(purchase);
            
            
        //Decrement Stock    
        decrementStock(purchaseItemList);

        tx.commit();

//        decrementStock(purchaseItemList);
//        checkStocklevel();

        //dispose
        eManager.close();
        emFactory.close();
        
        JOptionPane.showMessageDialog(null, "Purchase sucessfully ordered.\n\n" +
                "PurchaseId: " + purchase.getPurchaseId() +
                "\nTotal Price: " + purchase.getPrice(),
                "Purchase Sucessful!",
                JOptionPane.INFORMATION_MESSAGE);
    }

    private void decrementStock(ArrayList<PurchaseItem> purchaseItemList) {

        //EMFactory
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Napier_E-StorePU");

        //EntityManager
        EntityManager eManager = emFactory.createEntityManager();

        //Start Transaction
        EntityTransaction tx = eManager.getTransaction();
        tx.begin();



        Stock tmpStockItem = new Stock();
        PurchaseItem tmpPItem = new PurchaseItem();

        Iterator<PurchaseItem> it = purchaseItemList.iterator();
        while (it.hasNext()) {
            tmpPItem = it.next();
            tmpStockItem = eManager.find(Stock.class, tmpPItem.getArtNbr());
            tmpStockItem.setQuantity(tmpStockItem.getQuantity() - tmpPItem.getQuantity());



            eManager.persist(tmpStockItem);
        }

        tx.commit();

        //dispose
        eManager.close();
        emFactory.close();

        //Check for alert!
        if (tmpStockItem.getQuantity() <= MINSTOCK) {
            BL_Alert blAlert = new BL_Alert();

            blAlert.raiseMinStockAlert(tmpStockItem);
        }
    }
}
